package com.zqweb.gulimall.seckill.interceptor;

import com.zqweb.common.constant.AuthServerConstant;
import com.zqweb.common.vo.MemberUserInfoVo;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;

public class SeckillLoginInterceptor implements HandlerInterceptor {
    // 存储登陆的用户信息的threadLocal
    public static ThreadLocal<MemberUserInfoVo> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        AntPathMatcher matcher = new AntPathMatcher();
        boolean match1 = matcher.match("/seckillGoods", uri);
        if(match1){
            HttpSession session = request.getSession();
            MemberUserInfoVo memberUserInfoVo = (MemberUserInfoVo)session.getAttribute(AuthServerConstant.LOGIN_USER_KEY);
            if(memberUserInfoVo != null){
                threadLocal.set(memberUserInfoVo);
                return true;// 放行请求
            }else{
                response.setContentType("text/html;Charset=UTF-8");
                PrintWriter writer = response.getWriter();
                writer.println("<script>alert('请先进行登陆，再来继续操作！');location.href='http://auth.gulimall.com/login.html'</script>");

                session.setAttribute("errMsg","请先进行登录");
                response.sendRedirect("http://auth.gulimall.com/login.html");
                // Caused by: java.lang.IllegalStateException: Cannot create a session after the response has been committed

                return false;// 拦截请求，不能继续访问相应的资源
            }
        }
        // 对于非/seckillGoods的请求，都予以放行
        return true;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
